<script setup>
import { reactive, ref, watch } from "vue";
import { updateUserInfoApi} from '@/api/admin/user'
import {useRouter,useRoute } from 'vue-router'
import UserInfo from '@/components/userInfo.vue'
import updataUserInfo from '@/components/admin/updataUserInfo.vue';
import ArticleList from '@/components/articleList.vue'  
import {getUserInfoApi,} from '@/api/user.js'
import {getUserArticleListApi,addArticleWatchApi,likeArticleApi,} from '@/api/article.js'
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import {postFileApi} from '@/api/file'
import { postStatus } from "@/utils/globleVar";
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const userInfo = ref({})
userInfo.value = userStore.userInfo
const commentList = ref([])

//用作展示帖子列表
const showArticleList = reactive({
    articleList:[],
    pageInfo:{}
})
//一次请求获取到的帖子列表
const articleList = ref({})

getArticleList(0,userInfo.value.id)
async function getArticleList(pageIndex,userId){
    try{
        const resp = await getUserArticleListApi(pageIndex,userId)
        if(resp.data.code === 200){
            articleList.value = resp.data.data.content
            if(articleList.value.length !== 0){
                showArticleList.pageInfo = resp.data.data.page
                articleList.value.forEach((article)=>{
                    if(article.status === postStatus.approved){
                        showArticleList.articleList.push(article)
                    }
                })
            }
        }
    }catch(e){
        console.log(e)
    }
}

//点赞
const onClickLike=async(userId,postId)=>{
    try{
        await addArticleWatchApi(postId)
        await likeArticleApi(postId,userId)
        showArticleList.articleList = []
        const promises = [];
        const count = showArticleList.pageInfo.number+1
        for (let i = 0; i < count; i++) {
            promises.push(getArticleList(i,userId));
        }
        await Promise.all(promises);
    }catch(e){
        ElMessage.error(e.message)
    }
}

//点击评论按钮
const onClickComment = async (postId)=>{
    try{
        await addArticleWatchApi(postId)
        //进入帖子详情
         router.push({path:'/detailBox/article',query:{
            articleId : postId}})
    }catch(e){
        console.log(e)
    }
}

//获取下一页数据
const getMoreArticle = async (pageInfo)=>{
    if(pageInfo.totalPages === 1 || pageInfo.number+1 >= pageInfo.totalPages){
        return
    }else{
        getArticleList(pageInfo.number+1) 
    }
}

//控制是否出现修改用户信息弹窗
const showUpdateBoard=ref(false)
const showUserInfo = reactive({})


//编辑个人用户信息
const onEdit = ()=>{
    showUpdateBoard.value = true
    showUserInfo.value = userInfo.value
}
//参数校验绑定的对象

function changeValue(e) {
    this.$forceUpdate()
}


//修改头像时所需的其他信息 username password email
const reqData = ref({
    id:'',
    avatar:'',
    username:'',
    password:'',
    email:'',
    phone:'',
    summary:'',
    age:'',
}) 
setReqData(userInfo.value)
function setReqData(info){
    reqData.value.id = info.id,
    reqData.value.username = info.avatar,
    reqData.value.username = info.username,
    reqData.value.password = localStorage.getItem('password'),
    reqData.value.email = info.email, 
    reqData.value.phone = info.phone,
    reqData.value.summary = info.summary,
    reqData.value.age = info.age
}
//设置头像
const setHeadImg = async (file)=>{
    try{
        const response = await postFileApi(file)
        reqData.value.avatar = response.data.data[0]
        const resp = await updateUserInfoApi(reqData.value)
        if(resp.data.code === 200){
            //重新设置pinia 本地存储中的userInfo
            userStore.setUserInfo(resp.data.data)
            //设置reqdata
            setReqData(resp.data.data)
            ElMessage.success('头像更新成功')
        }
    }catch(e){
        console.log(e)
    }
}


//修改个人信息
const onConfirm =async (info)=>{
    //参数校验
  if(info.username.length > 0 && (info.username.length < 6 || info.username.length > 20)){
    ElMessage.warning('用户名长度在6~20之间')
    return
  }
  if(info.phone.length > 0 && info.phone.length !== 11){
    ElMessage.warning('请输入正确手机号')
    return
  }
  const inputEmail = info.email
  const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if(!reg.test(inputEmail)){
    ElMessage.warning('邮箱格式不正确，请重新输入')
    return
  }
  if('password' in info){
    if(info.password !== '' ){
      if(info.password.length < 6 || info.password.length > 16){
        ElMessage.warning('密码长度在6~16之间')
        return
      }
    } 
  }else{
    info.password = ''
  }
  try{
    const resp = await updateUserInfoApi(info)
    if(resp.data.code === 200){
        showUpdateBoard.value = false
        //重新设置pinia 本地存储中的userInfo
        const resp = await getUserInfoApi()
        userStore.setUserInfo(resp.data.data)
        //设置reqdata
        setReqData(resp.data.data)
        userInfo.value = resp.data.data
       // router.go(0)
        ElMessage.success('修改个人信息成功')
    }
  }catch(e){
    console.log(e)
  }
}
const reset = ()=>{
userInfoFormRef.value.resetFields()
showUpdateBoard.value = false
}
 //取消
 const onCancle = ()=>{
    showUpdateBoard.value = false
 }
</script>
<template>
<div class="box">
<!-- 触发弹出框按钮 -->
    <el-affix :offset="350">
    <el-button 
    type="primary"
    class="editButton"
    plain
    @click="onEdit">
        <el-icon><EditPen /></el-icon>
    </el-button>

    <!-- 修改个人信息弹出框 -->
    <el-dialog
    v-model="showUpdateBoard">
      <updataUserInfo
      :userInfo="showUserInfo"
      @updateUser="onConfirm"
      @cancle="onCancle"
      ></updataUserInfo>
    </el-dialog>
    </el-affix>
   <div>
    <!-- 用户个人信息 -->
    <UserInfo
    class="userInfo"
    @setHeadImg="setHeadImg"
    :shouUpload="true"
    :userInfo="userInfo"
    ></UserInfo>

    <!-- 用户文章列表 -->
    <ArticleList
    class="articleList"
    @clickLike="onClickLike"
    @queryList="getMoreArticle"
    @clickComment="onClickComment"
    :articleInfo="showArticleList"
    ></ArticleList>
   </div>
</div>
</template>

<style lang="scss" scoped>
.box{
    height: 85vh;
    overflow: scroll;
    padding: 20px;
    .userInfo{
        
    }
    .articleList{

    }
}
::-webkit-scrollbar{
    display: none;
    background-color: aliceblue;
}

</style>